<template>
	<view>
		<!-- <xiaoVideoElement :src="videoUrl"></xiaoVideoElement> -->
		<video @waiting="waiting" enable-progress-gesture="true" autoplay="true" @fullscreenchange="onFullscreenChange"
			play-btn-position='center' @controlstoggle='controlstoggle' ref="video" :custom-cache="false"
			enable-danmu='true' @timeupdate="onTimeUpdate" controls danmu-btn="true" :src="videoUrl" class="video"
			:danmu-list="danmuList" @controls="oncontrols" @play="onplay" @pause="onpause" id="video">
			<cover-view>
				<cover-view class="sendDanmuFull" v-show="showDanmuView&&fullScreen">
					<input v-model="danmuValue" type="text" v-show="showDanmuText" placeholder="在此处输入弹幕内容"
						class="danmu-text" />
					<i @tap='SendDanmu' class="iconfont icon-fasong"></i>
				</cover-view>
				<cover-view class="playOrPause" v-show="showDanmuView&&videoUrl!=''&&fullScreen">
					<button class="play" @click="pause" v-show="isplay"><i class="iconfont icon-gf-pause2"></i></button>
					<button class="play" @click="play" v-show="!isplay"><i class="iconfont icon-bofang"></i></button>
				</cover-view>
			</cover-view>
		</video>
		<view
			style="position: fixed;top: 8vh;transform: translateY(-50%);left: 50%;transform: translateX(-50%);background-color: transparent;"
			v-show="videoUrl!=''&&showDanmuView">
			<button class="play1" @click="pause" v-show="isplay"><i class="iconfont icon-gf-pause2"></i></button>
			<button class="play1" @click="play" v-show="!isplay"><i class="iconfont icon-bofang"></i></button>
		</view>
		<view class="body">
			<!-- 	<button @tap="sync">同步</button> -->
			<view class="item">
				<view @tap="selectVideo" :style="{ borderBottom: itemIndex == 0 ? 'white 2px solid' : 'none'}"
					class="selectVideo">投屏</view>
				<view @tap="chat" :style="{ borderBottom: itemIndex == 1 ? 'white 2px solid' : 'none'}" class="chat">聊天
				</view>
				<view class="partner">
					<image class="partnerimg" :src="partnerImg">
						<view v-show="!partnerOnline" class="partnerOffline"></view>
					</image>
					<view class="status" :style="{backgroundColor:partnerOnline?'limegreen':'darkgray'}"></view>
				</view>
				<i @tap="openSetting" class="iconfont icon-shezhi settings"></i>
			</view>
			<view class="selectVideoBody" v-if="itemIndex==0">
				<view @tap="back" v-show="plays.names.length>=1" class="return">
					&larr;
				</view>
				<view class="search">
					<input class="search-text" v-model="searchContext" type="text" placeholder="输入要搜索的影片名字" />
					<i class="iconfont icon-sousuo search-submit" @tap="search"></i>
				</view>
				<view class="search-context">
					<view @tap="selectItem(index)" class="search-item" v-for="(item,index) in videos.names"
						v-if="plays.names.length==0">
						{{item}}
					</view>
					<view @tap="playItem(index)" class="search-item" v-for="(item,index) in plays.names"
						v-if="plays.names.length>=1">
						{{item}}
					</view>
				</view>
				<view class="page">
					<view class="prePage" v-if="page>1&&plays.names.length<1">
						<i class="iconfont icon-shangyiyehoutuifanhui-xianxingyuankuang" @tap="toPage(-1)"></i>
						<view style="font-size: 10px;">上一页</view>
					</view>
					<view class="prePage" v-else>
					</view>
					<view class="nextPage" v-show="pageSize==24&&plays.names.length<1">
						<i class="iconfont icon-xiayiyeqianjinchakangengduo-xianxingyuankuang" @tap="toPage(1)"></i>
						<view style="font-size: 10px;">下一页</view>
					</view>
				</view>
			</view>
			<view class="chatBody" v-else>
				<scroll-view ref="scrollView" scroll-y="true" class="danmu-context" :scroll-top="scrollTopHeight"
					scroll-with-animation="true" scroll-into-view="bottom">
					<view class="danmu-item" v-for="item in chatList">
						<p class="danmu-date">{{item.month}}:{{item.hour}}:{{item.minute}}</p>
						<p class="danmu-content">{{item.text}}</p>
					</view>
					<view id="bottom"></view>
				</scroll-view>
				<view class="danmu-input">
					<input v-model="danmuValue" class="danmu-text" type="text" placeholder="在此处输入弹幕内容" />
					<i @tap="SendDanmu" class="iconfont icon-fasong sendDanmu" formType="submit"></i>
				</view>
			</view>
		</view>
		<view class="yy" :style="{'display':style.yy}"></view>
		<view class="settingList" :style="{'display':style.settingList}">
			<i class="iconfont icon-guanbi" @tap="closeSetting" style="float: right;font-size: 30px;"></i>
			<button @tap="idea">意见反馈</button>
			<button @tap="unBind">解除关系</button>
			<p>在两秒内点击五次即为确认解除关系</p>
		</view>
		<view class="ideas" :style="{'display':style.ideas}">
			<i class="iconfont icon-guanbi" style="float: right;font-size: 20px;"
				@tap="style.ideas='none',style.settingList='block'"></i>
			<textarea type="text" v-model="ideas"
				style="border-bottom: 20px;border-radius: 5px;background-color: ghostwhite;width: 90%;margin-left: 5%;height: 300px;margin-top: 30px;" />
			<button style="margin-top: 20px;" @tap="commitIdeas">提交建议</button>
		</view>
	</view>
</template>

<script>
	import xiaoVideoElement from '../../components/xiao-video-component/xiao-video-component.vue'
	export default {
		data() {
			return {
				videoUrl: "",
				itemIndex: 1,
				searchContext: "",
				danmuValue: '',
				danmuList: [],
				chatList: [],
				currentTime: 0,
				showDanmuView: false,
				fullScreen: false,
				showDanmuText: false,
				partnerOnline: false,
				partnerImg: '',
				partnerName: '',
				roomId: '',
				videos: {
					names: [],
					urls: []
				},
				plays: {
					names: [],
					urls: []
				},
				page: 1,
				pageSize: 0,
				scrollTopHeight: 5000, // 滚动条位置
				oldScrollTopHeight: 0, // 上一次滚动条位置
				isplay: false,
				ws: null,
				main: false,
				syncTime: 0,
				style: {
					yy: 'none',
					settingList: 'none',
					ideas: 'none'
				},
				unbind: {
					clickInterval: 2000, //设置点击的有效时间
					lastClickTime: 0, //上次点击的时间
					clickCount: 0, //已经点击的次数
					totalTime: 0, //几次点击的时长间隔总和
					needClickCount: 5 //需要点击的次数
				},
				ideas: '',
				showType: 0
			}
		},
		methods: {
			selectVideo: function() {
				this.itemIndex = 0
			},
			chat: function() {
				this.itemIndex = 1
			},
			search: function() {
				let that = this
				if (that.searchContext == '') {
					return
				}
				that.plays.names = []
				that.plays.urls = []
				that.ajax(that.url.baseUrl + 'movies?page=1&value=' + that.searchContext, "GET", null, function(r) {
					if (r.data.data.names != null) {
						that.videos.names = r.data.data.names
						that.videos.urls = r.data.data.urls
						that.page = 1
						that.pageSize = r.data.data.names.length
						return
					}
					uni.showToast({
						icon: 'none',
						title: '暂无影片'
					})
				})

				// this.searchContext = ''
			},
			SendDanmu: function() {
				let that = this
				if (that.danmuValue == '') {
					that.showDanmuText = that.showDanmuText == true ? false : true
					return
				}
				let value = this.danmuValue
				let currentTime = Math.round(that.currentTime)
				let date = new Date()
				let danmu = {
					text: that.danmuValue,
					color: that.getRandomColor(),
					time: currentTime
				}
				let chat = {
					text: "我:" + this.danmuValue,
					year: date.getFullYear(),
					month: date.getMonth(),
					day: date.getDay(),
					hour: date.getHours(),
					minute: date.getMinutes()
				}

				let data = {
					roomId: that.roomId,
					message: this.danmuValue,
					createTime: date
				}
				that.ajax(that.url.baseUrl + 'chat', 'PUT', data, function(r) {
					if (r.data.code != 200) {
						uni.showToast({
							icon: 'none',
							title: '发送失败'
						})
						return
					}
					that.danmu(danmu)
					that.chatList.push(chat)
					that.scrollToBottom()
					data = {
						data: {
							createTime: date,
							message: value
						},
						type: "chat"
					}
					let jsonData = JSON.stringify(data);
					uni.sendSocketMessage({
						data: jsonData
					})
				})
				this.danmuValue = ''
				this.showDanmuText = false
			},
			getRandomColor: function() {
				const rgb = []
				for (let i = 0; i < 3; ++i) {
					let color = Math.floor(Math.random() * 256).toString(16)
					color = color.length == 1 ? '0' + color : color
					rgb.push(color)
				}
				return '#' + rgb.join('')
			},
			onTimeUpdate(e) {
				this.currentTime = e.target.currentTime;
			},
			controlstoggle: function(e) {
				let showingControls = e.detail.show
				if (showingControls) {
					this.showDanmuView = true
				} else {
					this.showDanmuView = false
				}
			},
			onFullscreenChange(e) {
				console.log(e)
				if (e.detail.fullScreen) {
					this.fullScreen = true
				} else {
					this.fullScreen = false
				}
			},
			selectItem(index) {
				let that = this
				let url = that.videos.urls[index]
				that.ajax(that.url.baseUrl + 'getlist?url=' + url, 'GET', null, function(r) {
					// console.log(r.data)
					if (r.data.data.names != null) {
						that.plays.names = r.data.data.names
						that.plays.urls = r.data.data.urls

						return
					}
					uni.showToast({
						icon: 'none',
						title: '暂无播放源'
					})
				})
			},
			toPage(i) {
				let that = this
				that.page += i
				that.ajax(that.url.baseUrl + 'movies?page=' + that.page + '&value=' + that.searchContext, "GET", null,
					function(r) {
						console.log(r.data)
						if (r.data.data.names != null) {
							that.videos.names = r.data.data.names
							that.videos.urls = r.data.data.urls
							that.pageSize = r.data.data.names.length
							console.log(that.videos.names)

						}

						return
						uni.showToast({
							icon: 'none',
							title: '暂无影片'
						})
						that.videos.names = []
						that.videos.urls = []
					})
			},
			playItem(i) {
				let that = this
				that.videoUrl = that.plays.urls[i]
				that.main = true
				let data = {
					data: that.videoUrl,
					type: "selectVideo"
				}
				let jsonData = JSON.stringify(data)
				uni.sendSocketMessage({
					data: jsonData
				})
			},
			back() {
				this.plays.names = []
				this.plays.urls = []
			},
			scrollToBottom() {
				this.scrollTopHeight = this.scrollTopHeight + 200
			},
			onplay() {
				this.isplay = true
			},
			onpause() {
				this.isplay = false
			},
			danmu(danmu) {
				if (this.isplay) {
					console.log(danmu)
					this.danmuList.push(danmu)
				}
			},
			play() {
				let video = uni.createVideoContext('video')
				video.play()
				let data = {
					data: null,
					type: "playVideo"
				}
				let jsonData = JSON.stringify(data)
				uni.sendSocketMessage({
					data: jsonData
				})
			},
			pause() {
				let video = uni.createVideoContext('video')
				video.pause()
				let data = {
					data: null,
					type: "pauseVideo"
				}
				let jsonData = JSON.stringify(data)
				uni.sendSocketMessage({
					data: jsonData
				})
			},
			onTimeUpdate(event) {
				let that = this
				let video = event.target;
				that.currentTime = video.currentTime

				if (that.main) {
					let data = {
						type: "syncVideo",
						data: video.currentTime
					}
					let jsonData = JSON.stringify(data)
					uni.sendSocketMessage({
						data: jsonData
					})
				} else {
					let syncTime = Math.round(that.syncTime)
					if ((that.syncTime - video.currentTime) >= 5 || (video.currentTime - that.syncTime) >= 5) {
						let video = uni.createVideoContext('video')
						video.seek(syncTime)
					}
				}
			},
			waiting(event) {
				console.log(event)
			},
			openSetting() {
				this.style.yy = 'block'
				this.style.settingList = 'block'
			},
			closeSetting() {
				this.style.yy = 'none'
				this.style.settingList = 'none'
			},
			unBind() {
				let data = this.unbind
				data.clickCount++
				let date = new Date()
				if (data.clickCount != 1) {
					data.totalTime += date - data.lastClickTime
					if (data.totalTime > data.clickInterval) {
						data.totalTime = 0
						data.clickCount = 1
						data.lastClickTime = 0
					}
				}
				data.lastClickTime = date
				if (data.clickCount == data.needClickCount) {
					if (data.totalTime < data.clickInterval) {
						this.ajax(this.url.baseUrl + "bind", "DELETE", null, function(r) {
							uni.navigateTo({
								url: "/pages/bind/bind"
							})
							setTimeout(() => {
								uni.showToast({
									title: "关系解除成功",
									icon: 'none'
								})
							})
						})
					}
					data.totalTime = 0
					data.clickCount = 0
					data.lastClickTime = 0
				}
			},
			idea() {
				this.style.settingList = 'none',
					this.style.ideas = 'block'
			},
			commitIdeas() {
				let that = this
				this.ajax(that.url.baseUrl + "chat/ideas", "PUT", that.ideas, function(r) {
					uni.showToast({
						icon: 'none',
						title: "提交成功"
					})
					that.ideas = ''
				})
			}
		},
		onLoad(res) {
			let that = this
			that.partnerName = res.nickName
			that.partnerImg = res.image
			that.ajax(that.url.baseUrl + "chat", "GET", null, function(r) {
				let data = r.data.data
				if (data != null) {
					for (let i = 0; i < data.length; i++) {
						let chat = {}
						let date = new Date(data[i].createTime)
						if (data[i].userId == uni.getStorageSync("userId")) {
							chat = {
								text: "我:" + data[i].message,
								year: date.getFullYear(),
								month: date.getMonth(),
								day: date.getDay(),
								hour: date.getHours(),
								minute: date.getMinutes()
							}

						} else {
							chat = {
								text: uni.getStorageSync("nickName") + ":" + data[i].message,
								year: date.getFullYear(),
								month: date.getMonth(),
								day: date.getDay(),
								hour: date.getHours(),
								minute: date.getMinutes()
							}
						}
						that.chatList.push(chat)
					}
				}
				that.roomId = r.data.roomId
			})
			this.videoContext = uni.createVideoContext('video')
			let token = uni.getStorageSync("token")
			if (token == null || token == '') {
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}
			this.ws = uni.connectSocket({
				url: this.url.wsUrl + 'Room/' + uni.getStorageSync("userId"),
				success() {
					console.log('WebSocket链接成功');
				}
			});
			setTimeout(() => {
				let data = {
					type: "syncVideoUrl",
					data: null
				}
				let jsonData=JSON.stringify(data)
				uni.sendSocketMessage({
					data: jsonData
				})
			}, 500)
			uni.onSocketMessage(function(res) {
				let data = JSON.parse(res.data)
				if (data.type == 'online') {
					that.partnerOnline = true
				} else if (data.type == 'partnerOnline') {
					that.partnerOnline = true
					let date = new Date()
					let chat = {
						text: uni.getStorageSync("nickName") + "进入了房间",
						year: date.getFullYear(),
						month: date.getMonth(),
						day: date.getDay(),
						hour: date.getHours(),
						minute: date.getMinutes()
					}
					that.chatList.push(chat)
					that.scrollToBottom()
				} else if (data.type == 'offline') {
					that.partnerOnline = false
					let date = new Date()
					let chat = {
						text: uni.getStorageSync("nickName") + "离开了房间",
						year: date.getFullYear(),
						month: date.getMonth(),
						day: date.getDay(),
						hour: date.getHours(),
						minute: date.getMinutes()
					}
					that.chatList.push(chat)
					that.scrollToBottom()
					that.main=true
				} else if (data.type == 'chat') {
					data = JSON.parse(data.data)
					let date = new Date(data.createTime)
					let chat = {
						text: uni.getStorageSync("nickName") + ":" + data.message,
						year: date.getFullYear(),
						month: date.getMonth(),
						day: date.getDay(),
						hour: date.getHours(),
						minute: date.getMinutes()
					}
					let currentTime = Math.round(that.currentTime)
					let danmu = {
						text: data.message,
						color: that.getRandomColor(),
						time: currentTime
					}
					that.danmu(danmu)
					that.chatList.push(chat)
					that.scrollToBottom()
				} else if (data.type == "selectVideo") {
					that.videoUrl = data.data
					that.main = false
					that.danmuList = []
				} else if (data.type == "playVideo") {
					let video = uni.createVideoContext('video')
					video.play()
				} else if (data.type == "pauseVideo") {
					let video = uni.createVideoContext('video')
					video.pause()
				} else if (data.type == "syncVideo") {
					let video = uni.createVideoContext('video')
					data = JSON.parse(data.data)
					that.syncTime = data
				}else if (data.type == "syncVideoUrl") {
					that.videoUrl=data.data
				}else if (data.type == "getVideoUrl") {
					let data={
						data:that.videoUrl,
						type:"getVideoUrl"
					}
					let jsonData=JSON.stringify(data)
					uni.sendSocketMessage({
						data:jsonData
					})
				}
			})
		},
		onHide() {
			let that = this
			that.pause()
			uni.closeSocket({
				success() {
					console.log("WebSocket关闭成功")
				}
			})
			that.ws = ''
			that.main=false
		},
		onShow() {
			if (this.showType != 0) {
				this.ws = uni.connectSocket({
					url: this.url.wsUrl + 'Room/' + uni.getStorageSync("userId"),
					success() {
						console.log('WebSocket链接成功');
					}
				});
			}
			this.showType++
			if (this.videoUrl != '') {
				setTimeout(() => {
					this.play()
				}, 500)

			}
		}
	}
</script>

<style lang="less">
	@import "../../static/iconfont/icon.css";

	.ideas {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		width: 80%;
		left: 10%;
		background-color: #383838;
		height: 60vh;
		z-index: 999;
	}

	.yy {
		width: 100%;
		height: 100vh;
		background-color: gray;
		opacity: .9;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 800;
		// display: none;s

	}

	.settingList {
		width: 50%;
		// height: 60%;
		background-color: #383838;
		z-index: 999;
		position: fixed;
		top: 50%;
		left: 25%;
		// transform: translateX(50%);
		transform: translateY(-50%);
		border-radius: 10px;

		button {
			width: 80%;
			margin-top: 20%;
			margin-bottom: 10%;
		}

		p {
			color: ghostwhite;
			font-size: 10px;
			text-align: center;
		}
	}

	.video {
		width: 100%;
		height: 30vh;
		background-color: #383838;

		.playOrPause {
			z-index: 999;
			width: 10%;
			// height: 15vh;
			position: absolute;
			right: 45%;
			top: 50%;
			transform: translateY(-50%);

			.play {
				background-color: transparent !important;
				border: none !important;

				i {
					z-index: 999;
					text-align: center;
					font-size: 40px;
				}
			}


		}

	}

	.play1 {

		background-color: transparent !important;
		border: none !important;
		outline: none;

		i {
			z-index: 999;
			text-align: center;
			font-size: 40px;
		}
	}



	.sendDanmuFull {
		z-index: 999;
		position: absolute;
		bottom: 18%;
		right: 4%;
		color: white;
		display: flex;

		i {
			font-size: 30px;
		}
	}

	.body {
		margin-top: -4px;
		width: 100%;
		background-color: #383838;
		height: 70vh;

		.page {
			display: flex;
			justify-content: space-between;

			.prePage,
			.nextPage {
				width: 50%;
				text-align: center;
				// padding-bottom: 50px;
				box-sizing: border-box;

				i {
					font-size: 30px;
				}

				color: whitesmoke;
			}
		}

		.item {
			width: 100%;
			height: 40px;
			display: flex;

			.selectVideo,
			.chat {
				color: ghostwhite;
				display: inline-block;
				// width: 20%;
				width: calc(50% - 80px);
				height: 40px;
				background-color: aqua;
				background-color: #383838;
				box-shadow: 0;
				text-align: center;
				line-height: 40px;
			}

			.partner {
				width: 40px;
				height: 40px;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 5px;
				position: relative;

				.partnerimg {
					width: 35px;
					height: 35px;
					border-radius: 100px;
					position: absolute;
					border: 1px solid ghostwhite;
				}

				.partnerOffline {
					width: 35px;
					height: 35px;
					border-radius: 100px;
					background-color: gray;
					z-index: 999;
					position: absolute;
					opacity: .9;

				}

				.status {
					width: 5px;
					height: 5px;
					border-radius: 100px;

					position: absolute;
					right: 0;
					bottom: 0;
				}
			}

			.settings {
				width: 40px;
				height: 40px;
				margin-left: auto;
				text-align: center;
				font-size: 30px;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.selectVideoBody,
		.chatBody {
			// height: 60vh;
			width: 100%;
			background-color: #383838;
		}

		.selectVideoBody {
			margin-top: 15px;

			.return {
				position: absolute;
				top: 37.5%;
				left: 5%;
				color: whitesmoke;
				font-size: 30px;
				z-index: 999;
			}

			.search {
				margin-left: 25%;
				display: flex;
				align-items: center;

				.search-text {
					width: 50%;
					font-size: 10px;
					padding-left: 5px;
					color: white;
					border: 1px white solid;
					border-radius: 30px;
					height: 30px;
				}

				.search-submit {
					font-size: 30px;
				}
			}

			.search-context {
				height: 49vh;
				overflow: auto;
				overflow-x: hidden;
				width: 100%;

				// display: flex;
				.search-item {
					color: ghostwhite;
					font-size: 10px;
					margin: 3px;
					width: 45%;
					height: 3vh;
					float: left;
				}
			}
		}

		.chatBody {
			width: 100%;
			padding-top: 5px;
			width: 100%;

			.danmu-context {
				height: 56vh;
				overflow: auto;
				overflow-x: hidden;
				width: 100%;

				.danmu-item {
					.danmu-date {
						font-size: 10px;
						text-align: center;
						color: darkgrey;
						width: 100%;
					}

					.danmu-content {
						width: 100%;
						font-size: 20px;
						text-align: left;
						padding-left: 10px;
						color: whitesmoke;
						word-wrap: break-word;
						/* 允许在单词内换行 */
						word-break: break-all;
						/* 允许在单词内断行 */
					}
				}
			}

			.danmu-input {

				width: 100%;
				border-top: whitesmoke 1px solid;
				position: absolute;
				bottom: 0%;
				height: 6vh;
				display: flex;

				.danmu-text {
					width: 70%;
					border: 1px whitesmoke solid;
					border-radius: 10px;
					height: 20px;
					padding-left: 5px;
					margin: 0 auto;
					font-size: 15px;
					margin-top: 5px;
					color: whitesmoke;
				}

				.sendDanmu {
					position: absolute;
					right: 5%;
					margin-top: 10px;
					font-size: 20px;
					line-height: 15px;
					text-align: center;
				}
			}
		}
	}
</style>
